const laydate = layui.laydate
const laypage = layui.laypage
const form = layui.form
layui.use(function () {
    // 日期范围
    laydate.render({
        elem: "#ID-laydate-shortcut-range-date",
        range: true,
        shortcuts: [
            {
                text: "上个月",
                value: function () {
                    var value = [];
                    var date1 = new Date();
                    date1.setMonth(date1.getMonth() - 1);
                    date1.setDate(1);
                    date1.setHours(0, 0, 0, 0);
                    value.push(date1);
                    var date2 = new Date();
                    date2.setDate(1);
                    date2.setHours(0, 0, 0, 0);
                    date2 = date2.getTime() - 1;
                    value.push(new Date(date2));
                    return value;
                }()
            },
            {
                text: "这个月",
                value: function () {
                    var value = [];
                    var date1 = new Date();
                    // date1.setMonth(date1.getMonth() - 1);
                    date1.setDate(1);
                    date1.setHours(0, 0, 0, 0);
                    value.push(date1);
                    var date2 = new Date();
                    date2.setMonth(date2.getMonth() + 1);
                    date2.setDate(1);
                    date2.setHours(0, 0, 0, 0);
                    date2 = date2.getTime() - 1;
                    value.push(new Date(date2));
                    return value;
                }()
            },
            {
                text: "下个月",
                value: function () {
                    var value = [];
                    var date1 = new Date();
                    date1.setMonth(date1.getMonth() + 1);
                    date1.setDate(1);
                    date1.setHours(0, 0, 0, 0);
                    value.push(date1);
                    var date2 = new Date();
                    date2.setMonth(date2.getMonth() + 2);
                    date2.setDate(1);
                    date2.setHours(0, 0, 0, 0);
                    date2 = date2.getTime() - 1;
                    value.push(new Date(date2));
                    return value;
                }()
            }
        ]
    })
});

//todo ============================== 跳转新增文章 ========================================
document.querySelector('#btnAddCate').addEventListener('click', function () {
    window.parent.document.querySelector('#addart').click()
})

//todo ============================== 跳转修改文章 ========================================
document.querySelector('#tbody').addEventListener('click', function (e) {
    if (e.target.classList.contains('zx_pen')) {
        window.parent.document.querySelector('#editart').click()
        const id = e.target.dataset.id
        localStorage.setItem('id', id)
    }
})

//todo ============================== 分页模块 ========================================

let headers = {
    start_time: '',
    end_time: '',
    title: '',
    cateid: '',
    page: '1',
    limit: '10'
}

function getPage(total) {

    //执行一个laypage实例
    laypage.render({
        elem: 'page-box',//注意，这里的 test1 是 ID，不用加 # 号
        count: total, //数据总数，从服务端得到
        curr: headers.page, // 当前第几页(会决定第几个按钮高亮)
        limit: headers.limit, // 每页显示的条数
        limits: [10, 20, 40, 80, 100], //下拉框每一项的结果
        layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'], // 排版
        jump(obj, first) {
            headers.page = obj.curr
            headers.limit = obj.limit
            //首次不执行
            if (!first) {
                renderArt()
            }
        }
    })

}



//todo ============================== 渲染文章数据 ========================================
const data = localStorage.getItem('x-token')

function renderHtml(data) {
    $('#tbody').html(data.map((item, index) => {
        arr.push(item.ishot)
        arr1.push(item.istop)
        arr2.push(item.status)
        if (arr[index] !== 0) {
            arr[index] = 'checked'
        } else {
            arr[index] = ''
        }
        if (arr1[index] !== 0) {
            arr1[index] = 'checked'
        } else {
            arr1[index] = ''
        }
        if (arr2[index] === 0) arr2[index] = '待审核'
        if (arr2[index] === 1) arr2[index] = '草稿箱'
        if (arr2[index] === 2) arr2[index] = '已发布'
        if (arr2[index] === 3) arr2[index] = '已删除'
        const times = new Date(item.create_date)
        const getTime = times.toLocaleDateString().replace(/\//g, '-') + ' ' + times.toTimeString().substr(0, 8)
        return `
        <tr>
        <td>${item.id}</td>
        <td>${item.title}</td>
        <td>${item.title}</td>
        <td><img src="http://124.223.14.236:8060/${item.pic}" alt=""></td>
        <td>${getTime}</td>
        <td class="layui-form"><input type="checkbox" ${arr[index]} disabled name="ishot" lay-skin="switch"></td>
        <td class="layui-form"><input type="checkbox" ${arr1[index]} disabled name="istop" lay-skin="switch"></td>
        <td>${arr2[index]}</td>
        <td>
          <button type="button" class="layui-btn layui-btn-normal btn_edit zx_circle1"><i
              class="layui-icon layui-icon-edit zx_pen" style="font-size: 18px;" data-id=${item.id}></i></button>
          <button type="button" class="layui-btn layui-btn-xs layui-btn-danger btn_delete zx_circle1" data-id=${item.id}><i
              class="layui-icon layui-icon-delete zx_bin"></i></button>
        </td>
      </tr>
        `
    }).join(''))
}

let arr = []
let arr1 = []
let arr2 = []
function renderArt() {
    axios
        .get('/ydd_article/list', {
            params: headers
        })
        .then(({ data: { data: { data, count } } }) => {
            renderHtml(data)
            getPage(count)
            form.render()
        })
}

renderArt()

//todo ============================== 删除文章数据 ========================================

$('#tbody').on('click', '.btn_delete', function () {
    const id = $(this).data('id')
    // 弹出确认框
    layer.confirm('是否确认要删除？', { icon: 3, title: '提示' }, function (index) {
        axios
            .get(`/ydd_article/del?id=${id}`)
            .then(({ data: { errno } }) => {
                // 提示
                if (errno !== 0) return layer.msg('删除失败！')

                // ! 解决删除的bug
                //  当这一页只有一个删除按钮了，当进行删除的时候就会有bug
                //  思路：这一页就没有了，应该展示上一页的数据
                //  注意事项：当前页最小值是 1
                //  如何得知这一页只有一个删除按钮? ==> 获取删除按钮看个数

                if ($('.btn_delete').length === 1) headers.page = headers.page === 1 ? 1 : headers.page - 1


                layer.msg('删除成功')

                // 重新获取所有数据展示
                renderArt()
            })
        layer.close(index);
    })
})

//todo ============================== 筛选文章数据 ========================================

// 渲染列表选择框
axios
    .get('/ydd_cate/all')
    .then(({ data: { data } }) => {
    $('#zx_acatename').append(data.map(({ id, catename }) => `
    <option value="${id}">${catename}</option>
 `).join(''))
        form.render('select') //刷新select选择框渲染
    })

$('#zx_screen').on('submit', function (e) {
    e.preventDefault()
    const data = $(this).serialize()
    let start_time = data.replace(/20-%20/g, '').split('&')[2].split('%')[1]
    let end_time = data.replace(/20-%/g, '').split('&')[2].split('%')[0].replace(/time=/g, '')
    start_time = +new Date(start_time)
    end_time = +new Date(end_time)
    if (!(start_time || end_time)) {
        start_time = ''
        end_time = ''
    }
    const newData = data.replace(/&time=.*/g, '') + `&start_time=${start_time}&end_time=${end_time}&page=1&limit=10`
    axios.get(`/ydd_article/list?${newData}`)
        .then(({ data: { data: { data, count } } }) => {
            renderHtml(data)
            getPage(count)
            form.render()
        })
})

//todo ============================== 关闭搜索框功能 ========================================
$('#close').on('click', function () {
    $('#zx_header').toggle()
})

//todo ============================== 刷新表格功能 ========================================
$('#refresh').on('click', function () {
    self.location.reload()
})